/*
 * @Description:
 * @Autor: zzj
 * @Date: 2023-08-29 21:41:16
 * @LastEditors: zzj liberty666@aliyun.com
 * @LastEditTime: 2023-09-11 15:03:51
 * @FilePath: \vite-project\src\store\modules\user.ts
 */
// 创建用户相关的小仓库
import { defineStore } from 'pinia'
import { reqLogin } from '@/api/user'
import { loginForm, loginResponseData } from '@/api/user/type'
import { UserState } from './types/types'
import { SET_TOKEN, GET_TOKEN } from '@/utils/token'
// 引入常量路由
import { constantRoute } from '@/router/routes'
// 创建小仓库
let useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(), // 用户唯一标识token
      menuRoutes: constantRoute, // 仓库存储 生成菜单需要的数组（路由）
    }
  },
  actions: {
    async userLogin(data: loginForm) {
      // 登录
      const res: loginResponseData = await reqLogin(data)
      if (res.code == 200) {
        this.token = res.data.token as string
        // 本地持久化存储
        SET_TOKEN(res.data.token as string)
        // localStorage.setItem("TOKEN", (res.data.token as string))
        // 保证当前async函数返回成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data.message))
      }
    },
  },
  getters: {},
})
// 对外暴露获取小仓库的方法
export default useUserStore
